package com.william.jdbcplus.core.crud;

import com.william.jdbcplus.common.enums.DbType;
import com.william.jdbcplus.core.util.JdbcUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.sql.Connection;
import java.sql.SQLException;

@Getter
@Setter
public class CrudConfig {

    private JdbcTemplate jdbcTemplate;

    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    private RedisTemplate<String, ?> redisTemplate;

    private RedisLockRegistry redisLock;

    public CrudConfig(JdbcTemplate jdbcTemplate, NamedParameterJdbcTemplate namedParameterJdbcTemplate, RedisTemplate<String, ?> redisTemplate, RedisLockRegistry redisLock) {
        this.jdbcTemplate = jdbcTemplate;
        this.namedParameterJdbcTemplate = namedParameterJdbcTemplate;
        this.redisTemplate = redisTemplate;
        this.redisLock = redisLock;
    }

    public DbType getDbType() {
        DbType dbType = DbType.OTHER;
        Connection connection = null;
        try {
            connection = jdbcTemplate.getDataSource().getConnection();
            if (connection != null) {
                dbType = JdbcUtil.getDbType(connection.getMetaData().getURL());
            }
        } catch (SQLException e) {
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
            }
        }

        return dbType;
    }

    public String getDsURL() {
        String url = "";
        Connection connection = null;
        try {
            connection = jdbcTemplate.getDataSource().getConnection();
            if (connection != null) {
                url = connection.getMetaData().getURL();
            }
        } catch (SQLException e) {
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
            }
        }

        if (url.contains("?")) {
            url = url.substring(0, url.indexOf("?"));
        }

        return url;
    }

    public static void main(String[] args) {
        String url = "jdbc:mysql://192.168.0.98:3333/jeecg-boot?serverTimezone=UTC&characterEncoding=UTF-8&useUnicode=true&useSSL=false&tinyInt1isBit=false";
        if (url.contains("?")) {
            url = url.substring(0, url.indexOf("?"));
        }
        System.out.println(url);
    }
}
